"""
结果评价引擎实现
"""
from typing import Dict, List, Any, Optional
import logging
import pandas as pd
import numpy as np

from .base_engine import BaseEngine

logger = logging.getLogger(__name__)


class EvaluationEngine(BaseEngine):
    """
    结果评价引擎，负责对计算结果进行评价和分析
    """
    
    def __init__(self, config: Dict[str, Any]):
        """
        初始化评价引擎
        
        Args:
            config: 引擎配置
        """
        super().__init__(config)
        
        # 评价标准
        self.evaluation_criteria = config.get("evaluation_criteria", {})
        
        # 计算状态
        self._progress = 0
        self._is_cancelled = False
    
    def validate_input(self, input_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        验证输入数据
        
        Args:
            input_data: 输入数据
            
        Returns:
            验证结果
        """
        errors = []
        
        # 检查必填参数
        required_params = self.get_supported_parameters()
        for param in required_params:
            if param["required"] and param["name"] not in input_data:
                errors.append(f"缺少必填参数: {param['name']}")
        
        # 检查参数类型
        for param_name, param_value in input_data.items():
            param_def = next((p for p in required_params if p["name"] == param_name), None)
            if param_def:
                expected_type = param_def["type"]
                if not isinstance(param_value, eval(expected_type)):
                    errors.append(f"参数 {param_name} 类型错误，应为 {expected_type}")
        
        return {
            "valid": len(errors) == 0,
            "errors": errors
        }
    
    def execute(self, input_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        执行评价
        
        Args:
            input_data: 输入数据
            
        Returns:
            评价结果
        """
        # 重置状态
        self._progress = 0
        self._is_cancelled = False
        
        try:
            # 验证输入
            validation_result = self.validate_input(input_data)
            if not validation_result["valid"]:
                raise ValueError("输入数据验证失败: " + ", ".join(validation_result["errors"]))
            
            # 解析输入数据
            self._progress = 10
            calculation_results = input_data["calculation_results"]
            scene_info = input_data["scene_info"]
            
            # 执行评价
            self._progress = 30
            evaluation_result = self._perform_evaluation(calculation_results, scene_info)
            
            # 生成报告
            self._progress = 70
            report = self._generate_report(evaluation_result, scene_info)
            
            # 完成
            self._progress = 100
            
            return {
                "status": "success",
                "evaluation_result": evaluation_result,
                "report": report,
                "input_data": input_data
            }
            
        except Exception as e:
            logger.error(f"评价执行失败: {str(e)}", exc_info=True)
            return {
                "status": "error",
                "error": str(e),
                "input_data": input_data
            }
    
    def get_progress(self) -> float:
        """
        获取评价进度
        
        Returns:
            进度百分比
        """
        return self._progress
    
    def cancel(self) -> bool:
        """
        取消评价
        
        Returns:
            是否取消成功
        """
        self._is_cancelled = True
        return True
    
    def get_supported_parameters(self) -> List[Dict[str, Any]]:
        """
        获取支持的参数列表
        
        Returns:
            参数列表
        """
        return [
            {
                "name": "calculation_results",
                "type": "dict",
                "description": "计算结果数据",
                "required": True
            },
            {
                "name": "scene_info",
                "type": "dict",
                "description": "场景信息",
                "required": True
            },
            {
                "name": "evaluation_criteria",
                "type": "dict",
                "description": "评价标准",
                "required": False
            }
        ]
    
    def _perform_evaluation(self, calculation_results: Dict[str, Any], scene_info: Dict[str, Any]) -> Dict[str, Any]:
        """
        执行具体评价
        
        Args:
            calculation_results: 计算结果
            scene_info: 场景信息
            
        Returns:
            评价结果
        """
        # 根据计算结果类型执行不同的评价逻辑
        result_type = calculation_results.get("type", "")
        
        if result_type == "sum" or result_type == "average":
            # 数值型结果的评价
            return self._evaluate_numeric_results(calculation_results, scene_info)
        
        elif result_type == "correlation":
            # 相关性结果的评价
            return self._evaluate_correlation_results(calculation_results, scene_info)
        
        elif result_type == "regression":
            # 回归结果的评价
            return self._evaluate_regression_results(calculation_results, scene_info)
        
        else:
            raise ValueError(f"不支持的结果类型: {result_type}")
    
    def _evaluate_numeric_results(self, results: Dict[str, Any], scene_info: Dict[str, Any]) -> Dict[str, Any]:
        """
        评价数值型结果
        
        Args:
            results: 计算结果
            scene_info: 场景信息
            
        Returns:
            评价结果
        """
        evaluation = {
            "type": "numeric_evaluation",
            "content": {
                "core_conclusion": "",
                "key_metrics_analysis": "",
                "factors_analysis": "",
                "recommendations": ""
            }
        }
        
        # 获取评价标准
        criteria = self.evaluation_criteria.get("numeric", {})
        
        # 分析关键指标
        key_metrics = []
        for metric, value in results["results"].items():
            # 检查是否达到预期目标
            target = criteria.get(metric, {}).get("target", None)
            if target is not None:
                status = "达到" if value >= target else "未达到"
                key_metrics.append({
                    "metric": metric,
                    "value": value,
                    "target": target,
                    "status": status
                })
        
        # 生成核心结论
        if key_metrics:
            passed = sum(1 for m in key_metrics if m["status"] == "达到")
            total = len(key_metrics)
            evaluation["content"]["core_conclusion"] = f"{passed}/{total} 个关键指标达到预期目标"
        else:
            evaluation["content"]["core_conclusion"] = "无明确评价标准，请参考详细分析"
        
        # 生成关键指标分析
        analysis = "<ul>"
        for metric in key_metrics:
            analysis += f"<li>{metric['metric']}: 当前值 {metric['value']:.2f}, 目标值 {metric['target']:.2f} ({metric['status']})</li>"
        analysis += "</ul>"
        evaluation["content"]["key_metrics_analysis"] = analysis
        
        # 生成建议
        if key_metrics and any(m["status"] == "未达到" for m in key_metrics):
            failed_metrics = [m["metric"] for m in key_metrics if m["status"] == "未达到"]
            evaluation["content"]["recommendations"] = f"建议重点关注以下未达标指标: {', '.join(failed_metrics)}"
        else:
            evaluation["content"]["recommendations"] = "所有关键指标均达到预期，建议继续保持"
        
        return evaluation
    
    def _evaluate_correlation_results(self, results: Dict[str, Any], scene_info: Dict[str, Any]) -> Dict[str, Any]:
        """
        评价相关性结果
        
        Args:
            results: 计算结果
            scene_info: 场景信息
            
        Returns:
            评价结果
        """
        evaluation = {
            "type": "correlation_evaluation",
            "content": {
                "core_conclusion": "",
                "key_metrics_analysis": "",
                "factors_analysis": "",
                "recommendations": ""
            }
        }
        
        # 获取相关性矩阵
        corr_matrix = results["results"]
        
        # 分析强相关性
        strong_correlations = []
        for col1, correlations in corr_matrix.items():
            for col2, value in correlations.items():
                if col1 != col2 and abs(value) >= 0.7:  # 强相关性阈值
                    strong_correlations.append({
                        "variable1": col1,
                        "variable2": col2,
                        "correlation": value
                    })
        
        # 生成核心结论
        if strong_correlations:
            evaluation["content"]["core_conclusion"] = f"发现 {len(strong_correlations)} 组强相关性关系"
        else:
            evaluation["content"]["core_conclusion"] = "未发现显著的相关性关系"
        
        # 生成关键指标分析
        analysis = "<ul>"
        for corr in strong_correlations:
            direction = "正" if corr["correlation"] > 0 else "负"
            analysis += f"<li>{corr['variable1']} 与 {corr['variable2']} 存在{direction}相关性 ({corr['correlation']:.2f})</li>"
        analysis += "</ul>"
        evaluation["content"]["key_metrics_analysis"] = analysis
        
        # 生成建议
        if strong_correlations:
            evaluation["content"]["recommendations"] = "建议进一步分析强相关性变量之间的因果关系"
        else:
            evaluation["content"]["recommendations"] = "建议考虑其他分析方法或引入更多变量"
        
        return evaluation
    
    def _evaluate_regression_results(self, results: Dict[str, Any], scene_info: Dict[str, Any]) -> Dict[str, Any]:
        """
        评价回归结果
        
        Args:
            results: 计算结果
            scene_info: 场景信息
            
        Returns:
            评价结果
        """
        evaluation = {
            "type": "regression_evaluation",
            "content": {
                "core_conlection": "",
                "key_metrics_analysis": "",
                "factors_analysis": "",
                "recommendations": ""
            }
        }
        
        # 生成核心结论
        r_squared = results["r_squared"]
        if r_squared >= 0.7:
            evaluation["content"]["core_conclusion"] = f"模型拟合良好 (R² = {r_squared:.2f})"
        elif r_squared >= 0.5:
            evaluation["content"]["core_conclusion"] = f"模型拟合一般 (R² = {r_squared:.2f})"
        else:
            evaluation["content"]["core_conclusion"] = f"模型拟合较差 (R² = {r_squared:.2f})"
        
        # 生成关键指标分析
        analysis = "<ul>"
        for var, coef in results["coefficients"].items():
            influence = "正向" if coef > 0 else "负向"
            analysis += f"<li>{var}: 每增加1单位，因变量{influence}变化 {abs(coef):.2f}</li>"
        analysis += f"<li>截距项: {results['intercept']:.2f}</li>"
        analysis += "</ul>"
        evaluation["content"]["key_metrics_analysis"] = analysis
        
        # 生成建议
        if r_squared < 0.5:
            evaluation["content"]["recommendations"] = "建议检查模型假设或考虑添加更多解释变量"
        else:
            evaluation["content"]["recommendations"] = "模型可用于预测分析，建议进一步验证"
        
        return evaluation
    
    def _generate_report(self, evaluation_result: Dict[str, Any], scene_info: Dict[str, Any]) -> Dict[str, Any]:
        """
        生成评价报告
        
        Args:
            evaluation_result: 评价结果
            scene_info: 场景信息
            
        Returns:
            报告内容
        """
        return {
            "summary": {
                "scene_name": scene_info.get("name", "未命名场景"),
                "evaluation_type": evaluation_result["type"],
                "core_conclusion": evaluation_result["content"]["core_conclusion"]
            },
            "details": evaluation_result["content"]
        }